from flask import g, request

from enums.menu_app_code_enum import MenuAppCodeEnum
from mauth.mtoken import TokenStrategyFactory


class LoginUserHolder:
    """
    当前用户工具
    """

    @staticmethod
    def set(userData):
        # 将当前用户信息注入到这一次请求中，方便全局使用
        if userData is None:
            return
        g.current_user = userData
        g.current_user_id = userData.get("userId")

    @staticmethod
    def get():
        return g.current_user

    @staticmethod
    def get_user_id():
        """
        获取当前用户id
        """
        if g.current_user is None:
            return None
        return g.current_user.get("userId")

    @staticmethod
    def get_user_name():
        """
        获取当前用户名
        """
        if g.current_user is None:
            return None
        return g.current_user.get("userName")

    @staticmethod
    def before_request():
        """
        请求之前
        """
        token_strategy = TokenStrategyFactory.get_instance()
        # 获取当前用户信息
        token_strategy = TokenStrategyFactory.get_instance()
        token = request.headers.get(token_strategy.TOKEN_KEY, "")
        token = token.replace("Bearer ", "")
        userData = token_strategy.get(token)
        LoginUserHolder.set(userData)

    @staticmethod
    def get_app_code():
        """
        获取当前应用编码
        """
        if g.current_user is None:
            return MenuAppCodeEnum.PLATFORM.name.lower()
        return g.current_user.get("appCode", MenuAppCodeEnum.PLATFORM.name.lower())
